import { HttpException, HttpStatus, Injectable, Query } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import {
  CreateUserDto,
  LoginUserDto,
  UpdateUserDto,
  UserDetailDto,
} from './dto/user.dto';
import { User } from './entities/user.entity';

import { JwtTool } from '@/utils/tool';
import {
  AdminLoginUserDto,
  AdminUpdateUserDto,
  AdminUserPageReqDto,
  AdminUserResDto,
} from './dto/admin-user.dto';

@Injectable()
export class UserService {
  private jwt = new JwtTool();

  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
    // private readonly analyticsService: AnalyticsService,
  ) {}

  async create(user: CreateUserDto) {
    const findUser = await this.usersRepository.findOne({
      where: { phone: user.phone },
    });

    if (findUser) {
      throw new HttpException('该用户已存在', HttpStatus.OK);
    }

    const newUser = this.usersRepository.create({
      phone: user.phone,
      role: user.role,
      password: user.password,
      name: '用户',
      platform: 'APP',
      // height: user.height,
      // weight: user.weight,
      // birthDate: user.birthDate,
      // education: user.education,
      // comorbidities: user.comorbidities,
      // password: await this.jwt.hashPassword(user.password),
      // gender: user.gender,
      // platform: user.platform,
    });
    await this.usersRepository.save(newUser);
  }

  async login(user: LoginUserDto) {
    let findUserData = await this.usersRepository.findOne({
      where: { phone: user.phone, isDeleted: false, platform: 'APP' },
      select: [
        'platform',
        'userId',
        'phone',
        'password',
        'birthDate',
        'createdAt',
        'updatedAt',
        'name',
        'inflammatoryTendency',
        'comorbidities',
        'education',
        'gender',
        'height',
        'weight',
        'role',
        'totalPoint',
        'reminderTimes',
      ],
      relations: ['relations', 'relations.toUser'],
    });
    if (!findUserData) {
      throw new HttpException('用户不存在', 10003);
    }

    if (findUserData.role !== user.role) {
      throw new HttpException('角色不匹配', HttpStatus.BAD_REQUEST);
    }

    const isPasswordValid = user.password === findUserData.password;

    if (!isPasswordValid) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST);
    }

    console.log(findUserData.relations[0]?.toUser);
    // 如果用户是家属，登录的时候获取关联角色的 token
    if (findUserData.role === 'FAMILY' && findUserData.relations[0]?.toUser) {
      findUserData = findUserData.relations[0].toUser;
    }

    console.log(findUserData);
    const token = this.jwt.generateToken({
      ...findUserData,
      password: undefined,
    });

    return { token, user: findUserData };
  }

  async adminLogin(data: AdminLoginUserDto) {
    const findUserData = await this.usersRepository.findOne({
      where: { phone: data.phone, isDeleted: false, platform: 'ADMIN' },
      select: ['platform', 'userId', 'phone', 'password', 'name'],
    });
    if (!findUserData) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    // const isPasswordValid = await this.jwt.validatePassword(
    //   data.password,
    //   findUserData.password,
    // );
    const isPasswordValid = data.password === findUserData.password;

    if (!isPasswordValid) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST);
    }
    const token = this.jwt.generateToken({
      ...findUserData,
      password: undefined,
    });

    return token;
  }

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  async findPage(
    @Query() query: AdminUserPageReqDto,
  ): Promise<AdminUserResDto> {
    const { pageNo = 1, pageSize = 10, ...rest } = query;

    const [list, total] = await this.usersRepository.findAndCount({
      where: { isDeleted: false, platform: 'APP', ...rest },
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
    });
    return { list, total };
  }

  async findCurUser(userId: number): Promise<UserDetailDto | null> {
    const userDetail = await this.usersRepository.findOne({
      where: {
        userId,
      },
    });
    return userDetail;
  }

  async findOne(userId: number): Promise<UserDetailDto | null> {
    const userDetail = await this.usersRepository.findOne({
      where: {
        userId: userId,
      },
    });
    return userDetail;
  }

  update(userId: number, params: UpdateUserDto) {
    return this.usersRepository.save({
      userId,
      ...params,
    });
  }

  adminUpdate(params: AdminUpdateUserDto) {
    return this.usersRepository.save(params);
  }

  clearPoint(userId: number) {
    return this.usersRepository.save({
      userId,
      totalPoint: 0,
    });
  }

  count() {
    return this.usersRepository.count({
      where: { isDeleted: false },
    });
  }

  async fakeRemove(userId: number) {
    const findUser = await this.usersRepository.findOne({
      where: { userId, isDeleted: false },
    });
    if (!findUser) {
      throw new HttpException('用户不存在', HttpStatus.OK);
    }
    findUser.isDeleted = true;
    return this.usersRepository.save(findUser);
  }

  findFamily(userId: number) {
    return this.usersRepository.find({
      where: { userId, isDeleted: false },
      relations: ['family'],
    });
  }
}
